package com.project.web.system.controller.app;

import com.project.common.core.utils.exception.Result;
import com.project.common.core.utils.id.IDUtil;
import com.project.web.system.controller.common.BaseController;
import com.project.web.system.model.app.Menu;
import com.project.web.system.service.app.MenuService;
import com.project.web.util.exception.SYSTEM_RESP_CODE_ENUM;
import com.project.web.util.exception.SystemCustomException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @ClassName MenuController
 * @Description
 * @Author WYY
 * @Date 2020/8/13 4:46 PM
 * @Version 1.0
 */
@Api(tags = "【Web】菜单类目")
@RestController("menuController")
@RequestMapping("/system/auth/menu")
public class MenuController extends BaseController {

    Logger logger = LoggerFactory.getLogger(MenuController.class);

    @Autowired
    private MenuService menuService;

    @ApiOperation(value = "查询树形菜单")
    @GetMapping(value = "/getTree")
    public Result getTree(Long id) {

        if (null != id) {
            List<Menu> childrenNode = menuService.findChildrenNodes(id);
            if (CollectionUtils.isNotEmpty(childrenNode)) {
                return getResult(childrenNode);
            }
        }

        return getResult(null);
    }


    /**
     * 保存菜单
     */
    @ApiOperation(value = "保存菜单")
    @PostMapping(value = "/save")
    public Result save(@RequestBody Menu menu) {
        if (menu == null) {
            throw new SystemCustomException(SYSTEM_RESP_CODE_ENUM.MISS_PARAMETER);
        }
        menu.setId(IDUtil.getId());
        menu.setCreateDate(new Date());
        if (menu.getParentId()==null) {
            menu.setParentId(1l);
            menu.setGrade(1);
        } else {
            Menu byId = menuService.getById(menu.getParentId());
            if (byId != null) {
                menu.setGrade(byId.getGrade() + 1);
            }
        }
        menuService.save(menu);
        return getResult("保存成功");
    }


    /**
     * 编辑菜单
     */
    @ApiOperation(value = "编辑菜单")
    @PostMapping(value = "/edit")
    public Result edit(@RequestBody Menu menu) {
        if (menu == null) {
            throw new SystemCustomException(SYSTEM_RESP_CODE_ENUM.MISS_PARAMETER);
        }
        menu.setModifyDate(new Date());
        menuService.update(menu);
        return getResult("修改成功");
    }


    /**
     * 编辑菜单
     */
    @ApiOperation(value = "删除菜单")
    @GetMapping(value = "/delete")
    public Result delete(Long id) {
        if (id == null) {
            throw new SystemCustomException(SYSTEM_RESP_CODE_ENUM.MISS_PARAMETER);
        }
        menuService.delete(id);
        return getResult("删除成功");
    }


}
